package com.zy.ivideo.service;

import com.zy.ivideo.entity.AgreeEntity;
import com.zy.ivideo.entity.ResponseEntity;
import com.zy.ivideo.repository.AgreeRepository;
import com.zy.ivideo.repository.VideoMultitypeRepository;
import com.zy.ivideo.repository.VideoSimpleRepository;
import com.zy.ivideo.utils.MD5Util;
import com.zy.ivideo.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;

@Service
public class AgreeService {
    @Autowired
    AgreeRepository agreeRepository;

    @Autowired
    EntityManager entityManager;

    @Autowired
    VideoSimpleRepository videoSimpleRepository;

    @Autowired
    VideoMultitypeRepository videoMultitypeRepository;

    /**
     * 点赞
     * @param entity
     * @return
     */
    public ResponseEntity<AgreeEntity> agree(AgreeEntity entity){
        //生成md5码用于校验重复数据
        entity.setVerifycode(MD5Util.getMD5(entity.getItemcode()+entity.getSourceflag()+entity.getUserid()));
        AgreeEntity result = agreeRepository.save(entity);
        if (result!=null){
            int videoResult=0;
            if (result.getSourceflag()==0){
                videoResult=videoSimpleRepository.updateAgreeNum(1,entity.getItemcode());
            }else if (result.getSourceflag()==1){
                videoResult=videoMultitypeRepository.updateAgreeNum(1,entity.getItemcode());
            }
            if (videoResult>0){
                return ResponseUtils.success(result);
            }
            return ResponseUtils.failed("点赞失败");
        }
        return ResponseUtils.failed("点赞失败");
    }

    /**
     * 取消点赞
     * @param entity
     * @return
     */
    public ResponseEntity<Boolean> unAgree(AgreeEntity entity){
        try{
            agreeRepository.deleteById(entity.getId());
            int videoResult=0;
            if (entity.getSourceflag()==0){
                videoResult=videoSimpleRepository.updateAgreeNum(-1,entity.getItemcode());
            }else if (entity.getSourceflag()==1){
                videoResult=videoMultitypeRepository.updateAgreeNum(-1,entity.getItemcode());
            }
            if (videoResult>0){
                return ResponseUtils.success(true);
            }
            return ResponseUtils.failed("取消点赞失败");
        }
        catch (Exception ex){
            return ResponseUtils.failed("点赞失败，error:"+ex.getMessage());
        }
    }



}
